package com.game.frame;

import com.game.dao.Charts;
import com.game.frame.MyFrame;
import com.game.init.Main;
import com.game.utils.DataBaseUtil;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class TheChartsFrame extends MyFrame {
    private JPanel contentPane;
    private JTable theChartsTable;
    private JScrollPane theChartsTableScrollPane;
    private JLabel loadingLabel; // 添加加载提示标签

    public TheChartsFrame() {
        super();
        this.setTitle("排行榜页面");
        initComponents();
        loadChartsData(); // 在构造函数中直接加载数据
    }

    private void initComponents() {
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        // 创建返回按钮
        JButton backButton = new JButton("返回");
        backButton.addActionListener(e -> {
            Main.setStatus(0);
            dispose();
        });

        // 创建加载提示标签
        loadingLabel = new JLabel("正在加载排行榜数据...");
        loadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
        loadingLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        theChartsTableScrollPane = new JScrollPane();
        theChartsTable = new JTable();
        theChartsTableScrollPane.setViewportView(theChartsTable);

        // 使用 GroupLayout 进行布局
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        contentPane.setLayout(gl_contentPane);
        
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(gl_contentPane.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(backButton)
                        .addComponent(loadingLabel, GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
                        .addComponent(theChartsTableScrollPane, GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE))
                    .addContainerGap())
        );
        
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(backButton)
                    .addGap(10)
                    .addComponent(loadingLabel)
                    .addGap(10)
                    .addComponent(theChartsTableScrollPane, GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                    .addContainerGap())
        );
    }

    private void loadChartsData() {
    // 初始显示加载提示，隐藏表格
    loadingLabel.setVisible(true);
    theChartsTableScrollPane.setVisible(false);

    // 使用 SwingWorker 在后台加载数据
    SwingWorker<DefaultTableModel, Void> worker = new SwingWorker<>() {
        @Override
        protected DefaultTableModel doInBackground() throws Exception {
            DefaultTableModel model = new DefaultTableModel() {
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false; // 使表格不可编辑
                }
            };
            model.addColumn("玩家ID");
            model.addColumn("游戏时间(秒)");
            model.addColumn("分数");

            java.util.List<Object[]> data = getChartsData();
            for (Object[] row : data) {
                model.addRow(row);
            }
            return model;
        }

        @Override
        protected void done() {
            try {
                DefaultTableModel model = get();
                theChartsTable.setModel(model);
                
                // 设置表格样式
                theChartsTable.setRowHeight(25);
                theChartsTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 12));
                theChartsTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
                
                // 添加排序功能
                TableRowSorter<TableModel> sorter = new TableRowSorter<>(model);
                theChartsTable.setRowSorter(sorter);
                
                // 隐藏加载提示，显示表格
                loadingLabel.setVisible(false);
                theChartsTableScrollPane.setVisible(true);
                
            } catch (Exception e) {
                loadingLabel.setText("加载失败: " + e.getMessage());
                e.printStackTrace();
                JOptionPane.showMessageDialog(TheChartsFrame.this,
                        "获取排行榜数据失败: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    };

    worker.execute();
}

private java.util.List<Object[]> getChartsData() throws SQLException {
    java.util.List<Object[]> data = new ArrayList<>();
    try (Connection conn = DataBaseUtil.getConnection();
         PreparedStatement pstmt = conn.prepareStatement(
                 "SELECT * FROM charts ORDER BY CAST(score AS SIGNED) DESC LIMIT 1000")) {
        
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            Object[] row = new Object[]{
                rs.getString("gameid"),
                rs.getString("gametime"),
                rs.getString("score")
            };
            data.add(row);
        }
    }
    return data;
}
}